/*
 * @lc app=leetcode.cn id=295 lang=cpp
 *
 * [295] 数据流的中位数
 */

// @lc code=start
class MedianFinder {
public:
    //利用对顶堆来实现
    //up是小顶堆
    //down是大顶堆.
    //插入时候，如果比down堆的最大数小，则插入down，否则插入up
    priority_queue<int, vector<int>, greater<int>> up;
    priority_queue<int, vector<int>, less<int>> down; 
    
    /** initialize your data structure here. */
    MedianFinder() {

    }
    
    void addNum(int num) {
        if(down.size() == 0 || num < down.top()){
            down.push(num);
            if(down.size() >= up.size() + 2){
                up.push(down.top());
                down.pop();
            }
        }
        else{
            up.push(num);
            if(up.size() > down.size()){
                down.push(up.top());
                up.pop();
            }
        }
    }
    
    double findMedian() {
        if((down.size() + up.size()) % 2 == 1) return down.top();
        else return (down.top() + up.top()) / 2.0;
    }
};

/**
 * Your MedianFinder object will be instantiated and called as such:
 * MedianFinder* obj = new MedianFinder();
 * obj->addNum(num);
 * double param_2 = obj->findMedian();
 */
// @lc code=end

